import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Select, theme, Divider, Radio, Table, Space, Tag, Checkbox, Pagination, Switch, message, AutoComplete, Cascader, InputNumber, Upload } from 'antd';
import React, { useState, useEffect, useContext } from 'react';
import MyContext from '../../../utils/myContext'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import http from '../../../utils/fetchHttp'

//和上传有关的想法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

const { Option } = Select;// ---表单的内容

// ----以下是表格
// 表格
const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 12,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};
const App = () => {
    const { token } = theme.useToken();
    const [form] = Form.useForm();
    const listStyle = {
        textAlign: 'center',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        marginTop: 16,
    };
    const onFinish = (values) => {
        if (values.productService.length == 2) {
            values.productService = 2
        } else if (values.productService[0] == "正品保证") {
            values.productService = 0
        } else if (values.productService[0] == "里程抵扣兑换") {
            values.productService = 1
        }
        if (values.postage == false) {
            values.postage = 0
        } else {
            values.postage = 1
        }
        const formData = new FormData();
        formData.append('file', values.productUrl.file.originFileObj); // file是要上传的图片文件

        fetch('/api/upload', {
            method: 'POST',
            body: formData
        })
            .then(req => req.text())
            .then(req=>{
                values.productUrl=req;
                console.log('Received values of form: ', values);
                http({
                    url: '/product/addProduct',
                    method: 'post',
                    data: values
                }).then(res => {
                    if (res.code === 200) {
                        //获取成功
                        // res.data
                        message.success(res.msg);
                    }
                }).catch(err => {
                    message.error('获取所有商品数据失败！');
                })
            })
            .catch(error => console.error(error));
        
        
    };
    const onChange = (checked) => {
        console.log(`switch to ${checked}`);
    };
    const [selectionType, setSelectionType] = useState('checkbox')
    const [switchValue, setSwitchValue] = useState(true);
    const plainOptions = ['正品保证', '里程抵扣兑换'];
    const store = useContext(MyContext)


    ///////////以下都是头像相关的
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const handleChange = (info) => {
        // if (info.file.status === 'uploading') {
        //     setLoading(true);
        //     return;
        // }
        // if (info.file.status === 'done') {
        //     // Get this url from response in real world.
        //     getBase64(info.file.originFileObj, (url) => {
        //         setLoading(false);
        //         setImageUrl(url);
        //     });
        // }
        console.log('%c ======>>>>>>>>', 'color:orange;', 'info', info)
        //判断他的类型和大小
        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg';
        if (!isJpgOrPng) {
            return message.error('只能上传 jpeg/jpg/png 图片');
        }
        const isLt2M = info.file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            return message.error('最大只能上传2M的图片');
        }
        //将文件对象转成base64的地址，img才能显示出来
        getBase64(info.file.originFileObj, (url) => {
            setImageUrl(url);
        });

    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );
    const customRequest = () => {

    }


    return (
        <div>
            <div style={listStyle}>
                <div style={{ lineHeight: '2rem', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', height: '2rem', padding: '1rem' }}>
                    <h3>添加商品</h3>
                </div>
                <br />
                <br />
                <br />
                <div style={{ lineHeight: '20rem', }}>
                    <Form
                        {...formItemLayout}
                        form={form}
                        name="register"
                        onFinish={onFinish}
                        initialValues={{
                            productClassify1: "请选择一级分类", productClassify2: "请选择二级分类", productPay: "请选择"
                        }}
                        style={{
                            maxWidth: "60rem",

                        }}
                        scrollToFirstError
                    >
                        <Form.Item
                            name="productID"
                            label="商品货号"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品货号！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品货号" />
                        </Form.Item>

                        <Form.Item
                            name="productName"
                            label="商品名称"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品名称！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品名称" />
                        </Form.Item>

                        <Form.Item
                            label="商品图片"
                            name="productUrl"
                            rules={[{ required: true, message: '商品图片必选' }]}
                        >
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                onChange={handleChange}
                                customRequest={customRequest}
                            >
                                {imageUrl ? (
                                    <img
                                        src={imageUrl}
                                        alt="avatar"
                                        style={{
                                            width: '100%',
                                        }}
                                    />
                                ) : (
                                    uploadButton
                                )}
                            </Upload>
                        </Form.Item>

                        <Form.Item
                            name='productClassify1'//初始化动态变得数据
                            label='分类'
                            rules={[
                                {
                                    required: true,
                                    message: '请选择你的商品分类！',
                                },
                            ]}
                        >
                            <Select>
                                {store.productClassify1.map(a => (
                                    <Option key={a.classifyID} value={a.classifyID}>{a.classifyName}</Option>
                                ))}
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name='productClassify2'//初始化动态变得数据
                            label='~'
                            rules={[
                                {
                                    required: true,
                                    message: '请选择你的商品分类！',
                                },
                            ]}
                        >
                            <Select>
                                {store.productClassify2.map(a => (
                                    <Option key={a.classifyID} value={a.classifyID}>{a.classifyName}</Option>
                                ))}
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name='productPay'//初始化动态变得数据
                            label='支付方式'
                            rules={[
                                {
                                    required: true,
                                    message: '请选择你的支付方式！',
                                },
                            ]}
                        >
                            <Select>
                                <Option value={0}>支付宝支付</Option>
                                <Option value={1}>微信支付</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name='productBrand'//初始化动态变得数据
                            label='品牌'
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品品牌！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品品牌" />
                        </Form.Item>

                        <Form.Item
                            name='productPrice'//初始化动态变得数据
                            label='价格'
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品价格！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品价格" />
                        </Form.Item>

                        <Form.Item
                            name='productRule'//初始化动态变得数据
                            label='尺码'
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品尺码！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品尺码" />
                        </Form.Item>

                        <Form.Item
                            name='productColor'//初始化动态变得数据
                            label='颜色'
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品颜色！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品颜色" />
                        </Form.Item>

                        <Form.Item
                            name='productIDCard'//初始化动态变得数据
                            label='条形码'
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品条形码！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品条形码" />
                        </Form.Item>

                        <Form.Item
                            name='productNum'//初始化动态变得数据
                            label='库存'
                            rules={[
                                {
                                    required: true,
                                    message: '请输入你的商品库存！',
                                },
                            ]}
                        >
                            <Input placeholder="请输入你的商品库存" />
                        </Form.Item>

                        <Form.Item
                            name='productVideo'//初始化动态变得数据
                            label='商品视频'
                        >
                            <Input placeholder="请输入你的商品视频" />
                        </Form.Item>

                        <Form.Item
                            name='postage'//初始化动态变得数据
                            label='是否包邮'
                        >
                            <Switch checked={switchValue} />
                        </Form.Item>

                        <Form.Item
                            name='productService'//初始化动态变得数据
                            label='服务保证'
                        >
                            <Checkbox.Group options={plainOptions} />
                        </Form.Item>
                        <Form.Item {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit">
                                添加商品
                            </Button>
                        </Form.Item>
                    </Form>
                </div>

            </div>
        </div >
    )
};
export default App;